package com.dxyxx.framework;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Group;
import com.dxyxx.pojo.Order;
import com.dxyxx.pojo.OrderComment;
import com.dxyxx.pojo.OrderDetail;
import com.dxyxx.pojo.ResponseResult;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class OrderCommentActivity extends BaseActivity {
	private final static String ID = "id";
	private final static String PID = "pid";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS = "imageIds";
	private final static String AMOUNT = "amount";
	private TextView money;
	private List<OrderDetail> products = new ArrayList<OrderDetail>();
	private UserPreferences userPreferences;
	private ProgressDialog progressDialog;
	private TextView orderMoney;
	private TextView orderDeliveryType;
	private TextView et_dtime;
	private ImageView et_payType;
	private ViewGroup rootViewGroup;
	private com.dd.CircularProgressButton circleButton;
	private com.android.customized.FlexibleRatingBar ratingBar5;
	private String uuid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_ordercomment);
		initViews();

		rootViewGroup = (ViewGroup) findViewById(R.id.content);
		//you can set up view here or in XML
		rootViewGroup = (ViewGroup) findViewById(R.id.content);
		//网络查询 查询
		progressDialog = ProgressDialog.show(OrderCommentActivity.this, null, null);
		progressDialog.setContentView(R.layout.dialog_circle);
		// 根据id 拿到信息。
		RequestParams rp = new RequestParams();
		Bundle bundle = this.getIntent().getExtras();
		rp.add("id", bundle.getString("id"));
		uuid = bundle.getString("uuid");
		char type = uuid.charAt(0);
		String url = null;
		switch (type) {
		case 'o':
			url = "order/findById";
			break;
		case 'g':
			url = "gorder/findById";
			break;

		default:
			url = "order/findById";
			break;
		}
		HttpUtil.get(url, rp, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				AgainPlayer.makeCall(OrderCommentActivity.this, "网络好像出错了");
			}

			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				try {
					JavaType type = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Order.class);
					ResponseResult<Order> result = getObjectMapper().readValue(arg2, type);
					if (result.getCode() == 1) {
						Order order = result.getObject();
						orderDeliveryType.setText("自提");
						switch (order.getBufferInterval()) {
						case 0:
							et_dtime.setText("当天");
							break;
						case 1:
							et_dtime.setText("下单后第二天");
							break;
						case 2:
							et_dtime.setText("下单后第三天");
							break;

						default:
							et_dtime.setText("当天");
							break;
						}
						if (order.getPayType().equals("alipay")) {
							et_payType.setImageResource(R.drawable.alipay_icon);
						} else {
							et_payType.setImageResource(R.drawable.wechat);
						}
						//Order 
						if (order.getOrderDetails() != null) {
							for (OrderDetail od : order.getOrderDetails()) {
								View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
								((TextView) view.findViewById(R.id.price)).setText(od.getPrice() + "");
								((TextView) view.findViewById(R.id.amount)).setText("*" + od.getAmount() + "=  ");
								((TextView) view.findViewById(R.id.all)).setText(df.format(od.getPrice() * od.getAmount()));
								((TextView) view.findViewById(R.id.description)).setText(od.getProduct().getDescription());
								((TextView) view.findViewById(R.id.specification)).setText(od.getProduct().getSpecification());
								imageLoader.displayImage(baseImageURL + od.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
								rootViewGroup.addView(view);
							}
						}
						// GroupOrder
						Group group = order.getGroup();
						if (group != null) {//属于团购
							View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
							((TextView) view.findViewById(R.id.price)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.amount)).setText("*1" + "=  ");
							((TextView) view.findViewById(R.id.all)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.description)).setText(group.getProduct().getDescription());
							((TextView) view.findViewById(R.id.specification)).setText(group.getProduct().getSpecification());
							imageLoader.displayImage(baseImageURL + group.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
							rootViewGroup.addView(view);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};

			@Override
			public void onFinish() {
				progressDialog.dismiss();
				super.onFinish();
			}
		});

		ratingBar5 = (com.android.customized.FlexibleRatingBar) findViewById(R.id.flexibleRatingBar5);

		ratingBar5.setInteriorAngleModifier(1.5F);
		userPreferences = UserPreferences.getInstance(getApplicationContext());
		circleButton = (com.dd.CircularProgressButton) findViewById(R.id.orderCommentButton);
		//加载打分数据。
		circleButton.setIndeterminateProgressMode(true);//一直加载模式
		circleButton.post(new Runnable() {
			@Override
			public void run() {
				circleButton.performClick();//先启动
			}
		});

		circleButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (circleButton.getProgress() == 0) {//首次启动，要转动
					if (!first) {// 启动转动
						circleButton.setProgress(50);
						first = true;
					} else {// 提交 打分
						//需要注意 失效 问题。TODO
						RequestParams params = new RequestParams();
						params.add("order_id", uuid);
						params.add("score", (int) ratingBar5.getRating() + "");
						//				String orderDetails;
						progressDialog.show();

						HttpUtil.post("order_comment/add", params, new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
								AgainPlayer.makeCall(OrderCommentActivity.this, "网络好像出错了");
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// 登陆失效 返回的信息 {"code":-1,"info":"没有登陆","object":null}
								try {
									ResponseResult rr = getObjectMapper().readValue(arg2, ResponseResult.class);
									if (rr.getCode() == -1) {
										SimpleToast.info(OrderCommentActivity.this, "页面失效了");
										finish();
									} else if (rr.getCode() == 1) {
										circleButton.setText("打分成功");
										circleButton.setProgress(100);
									} else {
										SimpleToast.info(OrderCommentActivity.this, rr.getInfo());

									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							public void onFinish() {
								progressDialog.dismiss();
								super.onFinish();
							}
						});

					}
				} else if (circleButton.getProgress() == -1) {
					// 重新加载
					circleButton.setProgress(0);
					//circleButton.setText("请等待");
					//circleButton.performClick();//先启动
					callNetwork(uuid);
				} else if (circleButton.getProgress() == 100) {
					SimpleToast.info(OrderCommentActivity.this, "已经打过分了");

				}
			}

		});
		callNetwork(bundle.getString("uuid"));
	}

	private void callNetwork(String uuid) {
		HttpUtil.get("order_comment/byUuid?uuid=" + uuid, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				try {
					//					Thread.sleep(6000);
					JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, OrderComment.class);
					ResponseResult<OrderComment> rr = getObjectMapper().readValue(arg2, javaType);

					if (rr.getCode() == 1) {//已经打分
						OrderComment comment = rr.getObject();
						ratingBar5.setRating(comment.getScore());
						circleButton.setProgress(100);
						// 废掉 打分栏
						ratingBar5.setOnTouchListener(new OnTouchListener() {
							public boolean onTouch(View v, MotionEvent event) {
								return true;
							}
						});
					} else if (rr.getCode() == 2) {//待打分
						ratingBar5.setRating(3);
						circleButton.setProgress(100);
						circleButton.setProgress(0);

					} else {//加载失败
						circleButton.setProgress(-1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});

	}

	private boolean first = false;

	public void initViews() {
		ImageView back = (ImageView) findViewById(R.id.backImageButton);
		back.setImageResource(R.drawable.common_cancel_switcher);//替换样式
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				OrderCommentActivity.this.finish();
			}
		});
		ImageView next = (ImageView) findViewById(R.id.nextImageButton);
		next = (ImageView) findViewById(R.id.nextImageButton);
		next.setImageResource(R.drawable.common_accept_switcher);
		TextView title = (TextView) findViewById(R.id.title);
		money = (TextView) findViewById(R.id.money);
		title.setText("发表评论");
		title.setGravity(Gravity.CENTER);
		orderMoney = (TextView) findViewById(R.id.orderMoney);
		orderDeliveryType = (TextView) findViewById(R.id.orderDeliveryType);
		et_dtime = (TextView) findViewById(R.id.et_dtime);
		//		orderId = (TextView) findViewById(R.id.orderId);
		et_payType = (ImageView) findViewById(R.id.payIcon);

	}

}
